﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections;
using System.Linq;
using ScrumTable.BL.DM.Properties;
using ScrumTable.Common;
using ScrumTable.Common.Collections;
using ScrumTable.DL.Data.Schema;
using System.Collections.Generic;

#endregion

namespace ScrumTable.BL.DM.DataManagement
{
    /// <summary>
    /// Contains the basic information about a workflow.
    /// </summary>
    public class ScrumItemType : DomainBase
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private DomainCollection<Transition> _transitions;
        private DomainCollection<DomainMeta> _fieldMeta;
        private ScrumStateMapper _stateMapper;

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets a list of all tasks associated to the current user story.
        /// </summary>
        public DomainCollection<Transition> Transitions
        {
            get
            {
                if (_transitions == null)
                {
                    _transitions = new DomainCollection<Transition>(
                        true,
                        Context,
                        this,
                        ContextInternal.Data.Storage[Schema.TransitionSchema]);
                }
                return _transitions;
            }
        }

        /// <summary>
        /// Gets a list of all tasks associated to the current user story.
        /// </summary>
        public DomainCollection<DomainMeta> FieldMeta
        {
            get
            {
                if (_fieldMeta == null)
                {
                    _fieldMeta = new DomainCollection<DomainMeta>(
                        true,
                        Context,
                        this,
                        ContextInternal.Data.Storage[Schema.MetaSchema]);
                }
                return _fieldMeta;
            }
        }


        /// <summary>
        /// Gets the name of the current domain object. In most cases this
        /// property will contain the domain object title.
        /// </summary>
        public override string Name
        {
            get { return DataObject.GetData(Schema.TypeSchema.Name, string.Empty); }
            set { }
        }

        /// <summary>
        /// Gets the name of the current domain object. In most cases this
        /// property will contain the domain object title.
        /// </summary>
        public bool HasStrictWorkflow
        {
            get { return DataObject.GetData(Schema.TypeSchema.HasStrictWorkflow, true); }
        }

        /// <summary>
        /// Retrieves the state mappings.
        /// </summary>
        public ScrumStateMapper StateMappings
        {
            get
            {
                if (_stateMapper == null)
                {
                    _stateMapper = new ScrumStateMapper();
                    States.ForEach(_stateMapper.TryAddState);
                }
                return _stateMapper;
            }
        }


        /// <summary>
        /// Gets the parent collection instance.
        /// </summary>
        internal override IDomainCollection ParentCollection
        {
            get { return Parent.SearchCollection<ScrumItemType>(); }
        }

        /// <summary>
        /// Gets a collection which contains all child collections of the current
        /// domain object.
        /// </summary>
        internal override ICollection ChildCollections { get { return new IDomainCollection[] { Transitions, FieldMeta }; } }

        /// <summary>
        /// Gets the domain object schema of the current domain object.
        /// </summary>
        protected override SchemaBase DomainSchema { get { return Schema.TypeSchema; } }

        /// <summary>
        /// Gets the name of the current domain object. In most cases this
        /// property will contain the domain object title.
        /// </summary>
        protected IEnumerable<string> States
        {
            get
            {
                return from state in DataObject.GetData<IEnumerable<object>>(Schema.TypeSchema.States, new object[0])
                       select state.ToString();
            }
        }

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Returns true if the specified state change could be accomplished.
        /// </summary>
        /// <param name="currentState">Specifies the current state (from).</param>
        /// <param name="newState">Specifies the new state to validate (to).</param>
        public bool CanChangeState(ScrumState currentState, ScrumState newState)
        {
            if (currentState == null) { return false; }
            if (newState == null) { return false; }
            if (!StateMappings.Contains(currentState)) { return false; }
            if (!StateMappings.Contains(newState)) { return false; }
            if (Equals(currentState, newState)) { return true; }

            return !(from tsn in Transitions
                     where StateMappings[tsn.FromState] == currentState && StateMappings[tsn.ToState] == newState
                     select tsn).IsEmpty();
        }

        /// <summary>
        /// Returns true if the specified state change could be accomplished.
        /// </summary>
        public bool HasAllBidirections()
        {
            return (Transitions.Count == CalcAllTransitionCount(StateMappings.Count));
        }

        /// <summary>
        /// Validates the state change and throws an exception if the change
        /// is not supported.
        /// </summary>
        /// <param name="currentState">Specifies the current state (from).</param>
        /// <param name="newState">Specifies the new state to validate (to).</param>
        internal void ValidateStateChange(ScrumState currentState, ScrumState newState)
        {
            PreCondition.AssertNotNull(currentState, "currentState");
            PreCondition.AssertNotNull(newState, "newState");

            if (!CanChangeState(currentState, newState))
                throw new TransitionNotAllowedException(Name, currentState, newState);
        }

        /// <summary>
        /// Resets all child collections (IDomainCollection instances) of the
        /// current domain object.
        /// </summary>
        protected override void ResetChildCollections()
        {
            _transitions = null;
            _fieldMeta = null;
        }

        /// <summary>
        /// Initializes the mappings stored in the current instance.
        /// </summary>
        protected override void InitializeMappings()
        {
            base.InitializeMappings();

            PropertySchemaMappings.Add(Schema.TypeSchema.Name, "Name");
            PropertySchemaMappings.Add(Schema.TypeSchema.HasStrictWorkflow, "HasStrictWorkflow");
        }

        private int CalcAllTransitionCount(int stateCount)
        {
            return (stateCount - 1) * stateCount;
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}